<template>
  <div class='user-content'>
    <div class='header'>
      <h3 class='title'>{{ contentConfig?.header?.title ?? '数据列表' }}</h3>
      <el-button v-if='isCreate' type='primary' @click='createUser'>
        {{ contentConfig?.header?.btnTitle ?? '新建数据' }}
      </el-button>
    </div>
    <div class='table'>
      <el-table
        :data='pageList'
        border
        style='width: 100%'
        v-bind='contentConfig.childrenTree'
      >
        <template v-for='item in contentConfig.propsList' :key='item.prop'>
          <template v-if='item.type === "timer"'>
            <el-table-column align='center' v-bind='item'>
              <template #default='scope'>
                {{ scope.row[item.prop] }}
              </template>
            </el-table-column>
          </template>
          <template v-else-if='item.type === "custom"'>
            <el-table-column align='center' v-bind='item'>
              <template #default='scope'>
                <slot :name='item.slotName' v-bind='scope'></slot>
              </template>
            </el-table-column>
          </template>
          <template v-else>
            <el-table-column
              align='center'
              v-bind='item'
            />
          </template>
        </template>
        <el-table-column align='center' label='操作'>
          <template #default='scope'>
            <el-button
              v-if='isUpdate'
              :icon='Edit'
              text
              type='primary'
              @click='editUserFn(scope.row)'
            >编辑
            </el-button>
            <el-button
              v-if='isDel'
              :icon='Delete'
              text
              type='danger'
              @click='handleDel(scope.row.id)'
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class='pagination'>
      <el-pagination
        v-model:current-page='pageNum'
        v-model:page-size='pageSize'
        :page-sizes='[10, 20, 30]'
        small='small'
        layout='total, sizes, prev, pager, next, jumper'
        :total='pageTotalCount'
        @size-change='handleSizeChange'
        @current-change='handlePageNumChange'
      />
    </div>
  </div>
</template>

<script setup lang='ts'>
import useSystemStore from '@/stores/main/system/system'
import { computed, ref } from 'vue'
import { Delete, Edit } from '@element-plus/icons-vue'
import usePermissions from '@/hooks/usePermissions'
import {ElMessage} from "element-plus";

interface IProps {
  contentConfig: {
    pageName: string,
    header?: {
      title?: string,
      btnTitle?: string
    },
    propsList: any[],
    childrenTree?: any
  }
}

const emit = defineEmits(['createUserFn', 'editUserFn'])
const props = defineProps<IProps>()

const pageNum = ref(1)
const pageSize = ref(10)

const isCreate = usePermissions('system:' + props.contentConfig.pageName + ':create')
const isUpdate = usePermissions('system:' + props.contentConfig.pageName + ':edit')
const isDel = usePermissions('system:' + props.contentConfig.pageName + ':delete')
const isQuery = usePermissions('system:' + props.contentConfig.pageName + ':query')

const systemStore = useSystemStore()
fetchPageListData()
// systemStore.postPageListAction(props.contentConfig.pageName, { pageNum: pageNum.value, pageSize: pageSize.value })

const pageList = computed(() => systemStore.pageList)
const pageTotalCount = computed(() => systemStore.userTotalCount)

systemStore.$onAction(({ name, after }) => {
  // TODO: 存在隐患，分页数据无法切换，由于mock的原因无法测试
  console.log(name)
  after(() => {
    // 当触发pinia中action为以下三个名称的方法时，将页码重置为1
    if (name === 'deleteUserByIdAction' || name === 'editUserDataAction' || name === 'createUserDataAction') {
      pageNum.value = 1
    }
  })
})

// 页码相关逻辑
function handleSizeChange() {
  // 此处应传递修改页码之后请求数据
  fetchPageListData()
}

function handlePageNumChange() {
  // 此处应传递修改一页显示的条数之后请求数据
  fetchPageListData()
}

function fetchPageListData(formData: any = {}) {
  // 当用户没有查询权限时，我们就不需要返回数据给当前用户了
  systemStore.clearPageList()
  if (!isQuery) return

  let pageInfo = { pageNum: pageNum.value, pageSize: pageSize.value }
  formData = { ...formData, ...pageInfo }

  systemStore.postPageListAction(props.contentConfig.pageName, formData)
}

function handleDel(id: number) {
  systemStore.delByIdAction(props.contentConfig.pageName, id).then(() => {
    ElMessage.success('删除成功')
  })
}

// 新建用户
function createUser() {
  // 此处是在触发父组件的showModal事件，让弹出层弹出对话框
  emit('createUserFn')
}

// 编辑用户信息
function editUserFn(itemData: any) {
  emit('editUserFn', itemData)
}

defineExpose({ fetchPageListData })
</script>

<style scoped lang='less'>
.user-content {
  margin-top: 20px;
  margin-bottom: 10px;
  padding: 20px;
  align-items: flex-end;
  background-color: #ffffff;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;

    .title {
      font-size: 22px;
    }
  }

  .table {
    margin-top: 20px;
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}
</style>
